<?php

namespace app;

use extend\Table;
use extend\Upload;

class QList
{

    static $page = 1;
    static $user_id = 0;
    static $config;
    static $page_num = 10;

    static function checkAuth()
    {
        if (!s('qadmin') && !is_admin()) {
            return json('未登录或无权限访问', 0);
        }
        return true;
    }

    static function init()
    {
        $authCheck = self::checkAuth();
        if ($authCheck !== true) {
            return $authCheck;
        }

        $data = input();

        $action = $data['qlist'];

        self::$page = $data['page'] ?? 1;

        if (!self::auth()) {
            return json('非法访问', 0);
        }

        self::$user_id = call_user_func('get_user_id');

        if (method_exists(QList::class, $action)) {
            return call_user_func_array([QList::class, $action], [$data]);
        } else {
            return json('', 0, '');
        }
    }


    static function auth()
    {
        return true;
        $data = input('post.');

        $hash = $data['_'] ?? '';
        if (!$hash) {
            return false;
        }
        unset($data['_'], $data['app'], $data['_h_'], $data['qcmt'], $data['PHPSESSID']);

        $keys = array_keys($data);
        sort($keys);

        $md5 = md5(json_encode($keys));

        return $hash == $md5;
    }

    /**
     * 加载数据
     * @auth false
     * @param $params
     */
    static function load($params)
    {

        $limit_start = self::$page * (self::$page_num) - (self::$page_num);
        $limit_end = self::$page_num;


        $table_config = self::config($params, 'list');
        if (!$table_config) {
            return json('表格未配置', 0);
        }

        if ($table_config['list_fields'] && $table_config['pk'] && !in_array($table_config['pk'], $table_config['list_fields'])) {
            $table_config['list_fields'][] = $table_config['pk'];
        }

        $fields = [];


        array_map(function ($filed) use (&$fields, $table_config) {
            $fields[$filed] = [
                'title' => $table_config['field_titles'][$filed] ?? strtoupper($filed),
                'type' => $table_config['field_options'][$filed]['type'] ?? 'text',
                'option' => $table_config['field_options'][$filed]['option_value'] ?? '',
            ];
        }, $table_config['list_fields']);

        $db = db();

        //筛选
        if ($table_config['search_fields']) {
            foreach ($table_config['search_fields'] as $field) {
                $_P = $params['params'] ?? [];
                if ($field && isset($_P[$field]) && $_P[$field] !== '') {
                    $db->where($field, "%{$_P[$field]}%", 'like');
                }
            }
        }


        //where 
        if (isset($params['map']) && $params['map']) {
            foreach ($params['map'] as $key => $value) {
                $db->where($key, $value);
            }
        }

        if ($table_config['condition_fields']) {
            foreach ($table_config['condition_fields'] as $field => $condition_str) {
                if ($condition_str == 1) {
                    continue;
                }
                try {
                    $conditions = Table::parseConditionValue($condition_str, $field, $params, true);
                } catch (\Exception $e) {
                    return json($e->getMessage(), 0);
                }
                if ($conditions) {
                    foreach ($conditions[$field] as $condition) {
                        $db->where($field, $condition[1], $condition[0]);
                    }
                }
            }
        }

        $list = $db->withTotalCount()->get($table_config['table_name'], [$limit_start, $limit_end], array_values($table_config['list_fields']));

        return json(['list' => $list, 'search_fields' => $table_config['search_fields'], 'fields' => $fields, 'pk' => $table_config['pk'], 'total' => (int)$db->totalCount, 'page' => (int)self::$page, 'total_page' => ceil($db->totalCount / self::$page_num), 'sql' => $db->getLastQuery()], 200, '');
    }

    static function config($params, $act = 'edit')
    {

        $table_config = Table::getConfig($params['table'], $params['mode'], $act);

        return $table_config ?? [];
    }

    /**
     * 文件上传
     * @auth false
     * @param $params
     */
    static function upload($params)
    {

        $Uploader = new Upload();

        if (!isset($params['blob']) || !$params['blob']) {
            return json('');
        }

        if (!self::$user_id) {
            return json('请先登录', 0);
        }

        $dir = $params['type'] != 'image' ? 'comments/files' : 'comments/images';

        $file_name = $params['name'] ?? '';

        $res = $Uploader->saveRawFile($params['blob'], $dir, '', $params['type'] != 'image' ? 'mp3' : 'jpg', $file_name);

        return json($res);
    }


    static function toggle_switch($params)
    {
        if (!isset($params['table']) || !isset($params['id']) || !isset($params['field'])) {
            return json('参数不完整', 0);
        }

        $table = $params['table'];
        $id = $params['id'];
        $field = $params['field'];

        $table_config = self::config($params, 'list');
        if (!$table_config) {
            return json('表格未配置', 0);
        }

        $db = db();
        $current_value = $db->where($table_config['pk'], $id)->getOne($table, $field);

        if ($current_value === null) {
            return json('记录不存在', 0);
        }

        $new_value = (int)$current_value;

        $result = $db->where($table_config['pk'], $id)->update($table, [$field => $new_value]);

        if ($result) {
            return json('切换成功', 200);
        } else {
            return json('切换失败', 0);
        }
    }


    public static function deleteRow($params)
    {
        p($params);
        
        // 验证必要参数
        if (!isset($params['table']) || !isset($params['id']) || !isset($params['mode'])) {
            return ['code' => 400, 'msg' => '缺少必要参数'];
        }

        $table = $params['table'];
        $id = $params['id'];
        $mode = $params['mode'];

        try {
            // 获取数据库连接
            $db = db();

            // 开始事务
            $db->startTransaction();

            // 执行删除操作
            $result = $db->where('id', $id)->delete($table);

            if ($result) {
                // 提交事务
                $db->commit();
                return ['code' => 200, 'msg' => '删除成功'];
            } else {
                // 回滚事务
                $db->rollBack();
                return ['code' => 404, 'msg' => '记录不存在或已被删除'];
            }
        } catch (\Exception $e) {
            // 回滚事务
            if (isset($db)) {
                $db->rollBack();
            }
            return ['code' => 500, 'msg' => '删除失败,请稍后重试'];
        }
    }
}
